package com.example.alee.ALeeSpringWeb.factory;

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {

    @Override
    public org.springframework.core.env.PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        Resource resourceResource = resource.getResource();
        System.out.println("resource Resource info");
        if (!resourceResource.exists()) {
            System.out.println("resource not exist");
            return new PropertiesPropertySource(null, new Properties());
        } else if (
                resourceResource.getFilename().endsWith(".yml") ||
                        resourceResource.getFilename().endsWith(".yaml")) {
            System.out.println("resourceResource = {}" + resourceResource.getFilename());

            List<PropertySource<?>> sources = new YamlPropertySourceLoader()
                    .load(resourceResource.getFilename(), resourceResource);
            return sources.get(0);
        }
        return super.createPropertySource(name, resource);
    }
}
